﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Net.Configuration;

namespace GetExternalIP
{

    public class getExternalIP
    {
        /// <summary>
        /// Get External IP Address From http://checkip.dyndns.org/
        /// </summary>
        /// <returns></returns>
        static public string IP()
        {
            //Try Catch statement to keep application from crashing incase there an error occurs.
            try
            {
                String direction = "";
                WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
                using (WebResponse response = request.GetResponse())
                using (StreamReader stream = new StreamReader(response.GetResponseStream()))
                {
                    direction = stream.ReadToEnd();
                }

                //Search for the ip in the html
                int first = direction.IndexOf("Address: ") + 9;
                int last = direction.LastIndexOf("</body>");
                direction = direction.Substring(first, last - first);

                return direction;
            }
            catch (Exception e)
            {
                
                return e.ToString();
            }

        }
    }
}
